package com.example.dingtalklogin.service.executor;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.dingtalklogin.common.exception.CheckException;
import com.example.dingtalklogin.dao.User;
import com.example.dingtalklogin.dao.UserRepository;
import com.example.dingtalklogin.service.dto.DingtalkBindingCmd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
public class DingtalkBindingCmdExe {

    private UserRepository userRepository;

    @Autowired
    public DingtalkBindingCmdExe(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void execute(DingtalkBindingCmd cmd){
        cmd.validate();
        User user = userRepository.getById(cmd.getUserId());
        if(user == null){
            throw new CheckException("钉钉绑定用户" + cmd.getUserId() + "不存在！");
        }
        if(StringUtils.hasLength(user.getDingtalkUnionId())){
            throw new CheckException("用户" + cmd.getUserId() + "已经绑定过钉钉，请先解绑！");
        }

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.set(User::getDingtalkUnionId, cmd.getUnionId());
        updateWrapper.set(User::getLastModifiedBy, cmd.getOpUserId());
        updateWrapper.set(User::getLastModifiedDate, LocalDateTime.now());

        updateWrapper.eq(User::getId, user.getId());

        userRepository.update(updateWrapper);
    }
}
